<template>
  <div class="app-container" style="display: flex; flex-direction: column; height: calc(80vh)">
    <!-- Header 区域 -->
    <div class="header">
      <button class="nav-button" @click="goToPreviousStep">上一步</button>
      <div class="steps-container">
        <div v-for="(step, index) in steps" :key="index" :class="['step-box', { active: index === currentStepIndex }]">
          {{ step }}
        </div>
      </div>
      <button class="nav-button" @click="goToNextStep">下一步</button>
    </div>
    <!-- 表格部分 -->
    <div class="table-container">
      <div class="table-header">
        <span class="table-title">外购产品碳排放源分析</span>
      </div>
      <el-table :data="activityList" style="width: 100%" border>
        <!-- 单元过程 -->
        <el-table-column prop="activity.type" label="生产阶段" fixed="left">
          <template #default="{ row }">
            <div class="process-cell">
              <span>{{ row.type || "——" }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 生产活动 -->
        <el-table-column prop="activity.activityName" label="生产活动" fixed="left">
          <template #default="{ row }">
            <div class="process-cell">
              <span>{{ row.activityName || "——" }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 碳排放源 -->
        <el-table-column label="碳排放源">
          <template #default="{ row }">
            <div class="process-cell">
              <span>{{ row.emissions || "——" }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 表格部分 -->
    <div class="table-container" style="margin-top: 20px">
      <div class="table-header">
        <span class="table-title">生产制造碳排放源分析</span>
      </div>
      <el-table :data="finalList" style="width: 100%" :key="tableKey" border>
        <!-- 单元过程 -->
        <el-table-column prop="materialName" label="生产活动" fixed="left">
          <template #default="{ row }">
            <div class="process-cell">
              <span>
                {{ row.materialName ? (row.materialName === "产品装配" ? "产品装配" : row.materialName + "制造") : "——" }}
              </span>
            </div>
          </template>
        </el-table-column>
        <!-- 碳排放源 -->
        <el-table-column label="碳排放源">
          <template #default="{ row }">
            <div class="process-cell">
              <span>{{ row.emissions || "暂未定义" }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <div class="process-cell">
              <el-button type="primary" link :icon="EditPen" @click="goToModal(row)">内部工序碳排放清单</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script lang="tsx" setup name="useProtable">
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { EditPen } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { useTabsStore } from "@/stores/modules/tabs";
const tabStore = useTabsStore();
// import { ElMessage } from "element-plus";
// import { FlowChart } from "@/api/interface";
// import { ElMessage, ElMessageBox } from "element-plus";
const steps = ref(["产品碳排放源分析", "外购零部件碳排放值收集", "产品生产装配碳排放值收集"]);
const router = useRouter();
const route = useRoute();
const baseUrl = import.meta.env.VITE_BASE_URL;
/**当前指定的project编号 */
const currentProjectId = ref(route.params.projectId as string);

// 当路由 projectId 变化时同步更新
watch(
  () => route.params.projectId,
  val => {
    currentProjectId.value = val as string;
  }
);
// 自制物料列表
const activityList = ref([
  {
    type: "原材料",
    activityName: "灯罩垫块",
    emissions: "灯罩垫块的生产、运输排放"
  },
  {
    type: "原材料",
    activityName: "灯单盖板",
    emissions: "灯单盖板的生产、运输排放"
  },
  {
    type: "原材料",
    activityName: "环氧树脂",
    emissions: "环氧树脂的生产、运输排放"
  },
  {
    type: "原材料",
    activityName: "塑料",
    emissions: "塑料的生产、运输排放"
  },
  {
    type: "原材料",
    activityName: "不锈钢板",
    emissions: "不锈钢板的生产、运输排放"
  },
  {
    type: "原材料",
    activityName: "铝合金",
    emissions: "铝合金的生产、运输排放"
  }
]);

interface SelfMadeMaterialRow {
  projectId: number;
  materialId: number;
  materialName: string;
  emissions: string;
}

// 装配排放数据接口
interface AssemblyEmissionRow {
  projectId: number;
  emissions: string;
}

// 定义装配排放数据
const assemblyEmission = ref<AssemblyEmissionRow | null>(null);

// 合并后的最终展示数据
interface CombinedRow {
  materialId: number;
  materialName: string;
  emissions: string;
}
const finalList = ref<CombinedRow[]>([]);

// 构建合并后的表格数据
const buildTableData = () => {
  const base: CombinedRow[] = selfEmissionList.value.map(item => ({
    materialId: item.materialId,
    materialName: item.materialName,
    emissions: item.emissions
  }));
  if (assemblyEmission.value) {
    base.push({
      materialId: 0,
      materialName: "产品装配",
      emissions: assemblyEmission.value.emissions || ""
    });
  }
  finalList.value = base;
  tableKey.value += 1;
};

const selfEmissionList = ref<SelfMadeMaterialRow[]>([]);
// 产品装配碳排放源列表

// 添加表格 key 用于强制重新渲染
const tableKey = ref(0);

// 当前步骤索引
const currentStepIndex = ref(0);

const getSelfEmissionList = async () => {
  try {
    console.log("currentProjectId:", currentProjectId.value);
    const pid = route.params.projectId as string;
    const res = await axios.get(`${baseUrl}/api/carbon/getSelfMadeMaterial?projectId=${pid}`);
    selfEmissionList.value = res.data.data ?? [];
    buildTableData();
  } catch (error) {
    console.error(error);
    ElMessage.warning("获取自制物料失败");
  }
};

const getAssemblyEmission = async () => {
  try {
    const pid = route.params.projectId as string;
    const res = await axios.get(`${baseUrl}/api/carbon/initAssemblyEmission`, {
      params: { projectId: pid }
    });

    if (res.status === 200 && res.data?.code === 200) {
      // 正常返回（即使 emissions 为空字符串也视为成功）
      assemblyEmission.value = res.data.data;
    } else {
      // 仅当接口明确返回非 200 code 时才提示
      ElMessage.warning(res.data?.msg || "获取产品装配碳排放源失败");
    }
  } catch (error: any) {
    console.error(error);
    // 网络层面错误：记录日志，但不打扰用户（接口缺数据时视为未定义即可）
  } finally {
    // 无论成功与否都刷新表格，以避免空数据导致的错误提示
    buildTableData();
  }
};

onMounted(async () => {
  fetchActivityList();
  await getSelfEmissionList();
  await getAssemblyEmission();
});

const fetchActivityList = async () => {
  try {
    const res = await axios.get(baseUrl + `/api/carbon/getCarbonEmissionsSubById?projectId=${currentProjectId.value}`);
    console.log("res!:", res);
    activityList.value = res.data.data;
  } catch (error) {
    console.error("Error:", error);
    ElMessage.warning("获取外购物料失败");
    return;
  }
};
// 监听路由变化
watch(
  () => route.path,
  async () => {
    await getSelfEmissionList();
    await getAssemblyEmission();
  }
);

const goToPreviousStep = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/purposeScope/${currentProjectId.value}`);
};
/**下一步跳转 */
const goToNextStep = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/inventory/structureTree/${currentProjectId.value}`);
};
const goToModal = (row: any) => {
  // 跳转到工艺流程图页面
  if (row.materialName === "产品装配") {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push({
      path: `/lca/inventory/selfMadeEmission/${currentProjectId.value}/0/${row.materialId}`
    });
  } else {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push({
      path: `/lca/inventory/selfMadeEmission/${currentProjectId.value}/1/${row.materialId}`
    });
  }
  console.log("row!:", row);
};
</script>
<style>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  margin-bottom: 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.nav-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}
.nav-button:hover {
  background-color: #007d6a;
}
.steps-container {
  display: flex;
  justify-content: space-between;
  width: 80%;
  padding: 0 20px;
}
.step-box {
  position: relative;
  flex: 1;
  padding: 15px 10px;
  margin: 0 10px;
  color: #777777;
  text-align: center;
  cursor: pointer;
  background-color: #f9f9f9;
  border: 1px solid #dcdcdc;
  border-radius: 5px;
  transition: all 0.3s;
}
.step-box.active {
  font-weight: bold;
  color: #009688;
  background-color: #e6f5f3 !important;
  border-color: #009688;
}

/* 每个步骤框的箭头 */
.step-box::after {
  position: absolute;
  top: 50%;
  right: -20px;
  font-size: 20px;
  color: #009688;
  content: "→";
  transform: translateY(-50%);
}
.step-box:last-child::after {
  visibility: hidden;
}
.impact-container {
  height: 100vh;
  padding: 16px;
  background-color: var(--el-bg-color-page);
}
.table-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  margin-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.process-cell,
.equipment-cell {
  display: flex;
  gap: 8px;
  align-items: center;
}
.emission-sources {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.source-item {
  padding: 4px 8px;
  font-size: 13px;
  border-radius: 4px;
}
.source-item.input {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-5);
}
.source-item.output {
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
  border: 1px solid var(--el-color-success-light-5);
}
.consumption-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.consumption-item {
  display: flex;
  gap: 8px;
  align-items: center;
}
.amount {
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.unit {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}
.divider {
  height: 1px;
  margin: 8px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}
.source-type {
  padding: 8px;
  color: var(--el-text-color-regular);
}
:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-color-primary-light-9);
  --el-table-row-hover-bg-color: var(#f5f7fa);
  --el-table-row-height: auto;
  --el-table-padding: 12px;
}
:deep(.el-table__cell) {
  padding: 12px !important;
}
:deep(.el-table th) {
  font-weight: 600;
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: var(--el-color-primary-light-9);
}
.io-type {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.io-item {
  padding: 4px 8px;
  font-size: 13px;
  text-align: center;
  border-radius: 4px;
}
.io-item.input {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-5);
}
.io-item.output {
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
  border: 1px solid var(--el-color-success-light-5);
}
.header-buttons {
  display: flex;
  gap: 10px;
}
.calc-params-dialog :deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  max-height: 80vh;
}
.calc-params-dialog :deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
}
.method-select {
  padding: 20px;
}
.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
.el-descriptions {
  margin: 0;
}
:deep(.el-descriptions__cell) {
  padding: 8px 12px;
}
.factor-details {
  padding: 8px;
}
.factor-title {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.factor-select {
  display: flex;
  gap: 8px;
  align-items: center;
}
.selected-factor {
  font-weight: 600;
  color: var(--el-color-primary);
}
.no-factor {
  color: var(--el-text-color-secondary);
}
</style>
